<?php

namespace app\admin\controller;

use app\admin\validate\District as ValidateDistrict;
use app\admin\model\AdminLog;
use app\common\model\District as DistrictModel;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 区域管理管理
 *
 * @icon fa fa-users
 */
class District extends Backend
{

    /**
     * @var \app\common\model\District
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('District');
        $this->assign('typeList', DistrictModel::getTypeList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $other_where = [];
            if(isset($filter['type']) && $filter['type']){
                $other_where = 'type & '.$filter['type'];
            }

            $parent_id = $this->request->param('parent_id', 28141);
            $o_where = ['parent_id'=>$parent_id];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id', 'name'], false);
            $list = $this->model
                ->where($where)
                ->where($o_where)
                ->where($other_where)
                ->order($sort, $order)
                ->paginate($limit);

            $title = "广东省深圳市";
            if($parent_id != 28141){
                $title .= DistrictModel::where('id', $parent_id)->value('name');;
            }
            foreach ($list as &$item) {
//                $item['address_name'] = '';
//                if($parent_id == 28141){
//                    $item['address_name'] .= '广东省';
//                }else{
//                    $item['address_name'] .= '广东省深圳市';
//                }
//                $item['address_name'] .= DistrictModel::where('id', $item['parent_id'])->value('name');
                $item['type'] = DistrictModel::getTypeText($item['type']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items(), 'title' => $title);

            return json($result);
        } else {
            if (!isset($_REQUEST['parent_id'])) {
                return redirect('index', ['parent_id' => 28141]);
            }
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $validate = new ValidateDistrict();
                if (!$validate->check($params, [], 'add')) {
                    $this->error($validate->getError());
                }

                if (!$params['parent_id']) {
                    $params['level'] = DistrictModel::LEVEL_COUNTRY;
                } else {
                    $districtInfo = model('District')->where('id', $params['parent_id'])->find();
                    if (!$districtInfo) {
                        $this->error('上级不存在！');
                    }
                    if ($districtInfo['level'] == DistrictModel::LEVEL_STREET) {
                        $this->error('街道不能再添加下级了！');
                    }

                    switch ($districtInfo['level']) {
                        case DistrictModel::LEVEL_COUNTRY:
                            $level = DistrictModel::LEVEL_PROVINCE;
                            break;
                        case DistrictModel::LEVEL_PROVINCE:
                            $level = DistrictModel::LEVEL_CITY;
                            break;
                        case DistrictModel::LEVEL_CITY:
                            $level = DistrictModel::LEVEL_DISTRICT;
                            break;
                        case DistrictModel::LEVEL_DISTRICT:
                            $level = DistrictModel::LEVEL_STREET;
                            break;
                        default:
                            $this->error('类型错误！');
                            break;
                    }

                    $params['level'] = $level;
                }

                $types = $params['type'];
                $type = 0;
                foreach($types as $v){
                    if($v){
                        $type = $type | $v;
                    }
                }
                $params['type'] = $type;
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $this->savePublicAssign([
                'parent_id' => $this->request->get('parent_id')
            ]);
        }

        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $types = $params['type'];
                $type = 0;
                foreach($types as $v){
                    if($v){
                        $type = $type | $v;
                    }
                }
                $params['type'] = $type;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->savePublicAssign([
            'parent_id' => $row['parent_id']
        ]);
        $types = [];
        if($row['type'] & DistrictModel::TYPE_SHOP){
            $types[] = DistrictModel::TYPE_SHOP;
        }
        if($row['type'] & DistrictModel::TYPE_STORE){
            $types[] = DistrictModel::TYPE_STORE;
        }
        $this->view->assign("types", $types);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    protected function savePublicAssign($requestParam)
    {
        $parentId = $requestParam['parent_id'];
        if ($requestParam['parent_id'] > 0) {
            $parentId = model('District')->where('id', $requestParam['parent_id'])->value('parent_id');
        }
        $parentId = intval($parentId);
        if($parentId == 27833){
            $parentList[] = ['id'=> 28141, 'name'=>'深圳市']   ;
        }else{
            $parentList = DistrictModel::getAllDistrict($parentId);
        }
        $parentSelectList = [];
        $parentSelectList['0'] = '请选择';
        foreach ($parentList AS $value) {
            $parentSelectList[$value['id']] = $value['name'];
        }
        $this->assign('parentList', $parentSelectList);
    }

    public function district_list()
    {
        AdminLog::setTitle('地区列表');
        $parent_id = $this->request->param('parent_id', 1);
        $type = $this->request->param('type', '');
        $o_where = [];
        if($type){
            $o_where = 'type & '.$type;
        }
        $list = model('District')->where('parent_id', $parent_id)->where($o_where)->select();
        foreach($list as &$item){
            if($type == DistrictModel::TYPE_SHOP){
                $item['name'] = $item['shop_name'];
            }
        }
        $this->success('OK', '', $list);
    }

    public function district_all_list()
    {
        AdminLog::setTitle('地区列表');
        $this->model = model('District');
        return parent::index();
    }



    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    public function get_district()
    {

        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $o_where = [];
        $type = $this->request->param('type', DistrictModel::TYPE_SHOP);
        if($type){
            $o_where = "type & ". $type;
        }
        $list = [];
        $total = $this->model->where($where)->where($o_where)->where('parent_id', 28141)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->where('parent_id', 28141)
                ->where($o_where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                        'account_prefix'      => isset($item['account_prefix']) ? $item['account_prefix'] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
